#-------------------------------------------------------------------------------
#!	\file		extract.awk
#!
#!	\brief		Extract defines from C header file.
#!
#!	\details
#!				This awk script extracts defines from a C header file
#!				and creates a lua table suitable to be installed into
#!				my peripheral emulator...
#!
#!	\author		ACV
#!
#!	\version	1
#!
#!	\date		2013-03-04
#!
#-------------------------------------------------------------------------------

#-------------------------------------------------------------------------------
#	Before the file is processed:
#	- Create the lua file name from the c header
#	- Start the lua script
#-------------------------------------------------------------------------------
BEGIN {
	first = 1
	base = 0
	split(ARGV[1],in_name,".")
	out_name = in_name[1] ".lua"

	printf("---------------------------------------------------------------------\n") > out_name
	printf("-- %s registers\n",in_name[1]) > out_name
	printf("-- extracted from: %s\n",ARGV[1]) > out_name
	printf("-- Generation Date: %s\n",strftime()) > out_name
	printf("--\n") > out_name
	printf("-- This is a generated file.  It is created by the extract.awk awk script.\n") > out_name
	printf("--\n") > out_name
	printf("-- Do not edit.\n") > out_name
	printf("---------------------------------------------------------------------\n") > out_name
	printf("%s_registers = {\n",in_name[1]) > out_name
}

#-------------------------------------------------------------------------------
#	Toss out comments
#-------------------------------------------------------------------------------
$1 ~/^\/\// {
#	print "comment:" $0
	next
}

#-------------------------------------------------------------------------------
#	When a define is matched:
#	- extract the symbol and the value
#	- write out a low and high register definition to the Lua table
#-------------------------------------------------------------------------------
$1 ~/^#define/ {
	sym = $2
	val = strtonum($3)

	if (first == 1) {
		base = val
		first = 0
	}
	else {
		reg_lo = $2 "_low"
		reg_hi = $2 "_high"
		printf("\t%-48s= 0x%08X,\n", reg_lo, base+val) > out_name
		printf("\t%-48s= 0x%08X,\n", reg_hi, base+val+4) > out_name
	}
}

#-------------------------------------------------------------------------------
#	At the end of the file:
#	- Write out the end of the lua table
#	- close out the Lua file
#-------------------------------------------------------------------------------
END {
	printf("}") > out_name
	close(out_name)
}

#
#	End: extract.awk
#
